package pers.archives.loginToken.authentication;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import pers.archives.common.constant.ResponseConstant;
import pers.archives.common.entity.SecurityUser;
import pers.archives.common.ov.common.CommonResponse;
import pers.archives.common.ov.common.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
 *@program:archives-parent
 *@author: 赵浩浩
 *@Time: 2020/9/12  12:53
 */
@Component
public class ArchivesAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    @Autowired(required = false)
    private ClientDetailsService clientDetailsService;

    @Autowired(required = false)
    private AuthorizationServerTokenServices authorizationServerTokenServices;


    /**
     * 登录成功处理
     * @param request
     * @param response
     * @param authentication
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        //设置返回值编码格式
        response.setContentType(ResponseConstant.RESPONSE_CONTENT);
        //获取请求头中的信息
        String header = request.getHeader("Authorization");
        //查看请求头信息是否合法
        if (header == null || !header.startsWith("Basic ")) {
            throw new UnapprovedClientAuthenticationException("请求头中无client信息");
        }
        //拆分请求头信息
        String[] tokens = extractAndDecodeHeader(header, request);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        //比对clientId是否存在
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        //查看clientDetails 是否一致
        if (clientDetails == null) {
            throw new UnapprovedClientAuthenticationException("clientId对应的配置信息不存在:" + clientId);
        } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
            throw new UnapprovedClientAuthenticationException("clientSecret不匹配:" + clientId);
        }
        //创建token
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId, clientDetails.getScope(), "custom");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        //获取登陆成功的用户
        SecurityUser userInfo = ((SecurityUser) authentication.getPrincipal());
        userInfo.setToken(token.getValue());
        CommonResponse<SecurityUser> userCommonResponse = new CommonResponse<>(ResponseCode.USER_LOGIN_SUCCESS,
                userInfo);
        PrintWriter writer = response.getWriter();
        writer.write(userCommonResponse.toString());
        writer.flush();
        writer.close();
    }

    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {

        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }

        String token = new String(decoded, "UTF-8");

        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[] { token.substring(0, delim), token.substring(delim + 1) };
    }
}
